import { http } from '@/utils';

// 获取频道数据
export const getChannels = () => {
  return async (dispatch) => {
    const res = await http.get('/channels');
    console.log('channels res', res);

    // 把频道数据保存到reducer
    dispatch({ type: 'article/getChannels', payload: res.data.data.channels });
  };
};

// 获取文章列表数据
export const getArticles = (params) => {
  return async (dispatch) => {
    // 发起文章列表请求
    console.log('params', params);
    // 组装接口需要的数据
    let queryParams = {};
    // 文章状态-不传为全部
    if (params.status !== -1) {
      queryParams.status = params.status;
    }
    // 处理频道-不传为全部
    if (params.channelId !== -1) {
      queryParams.channel_id = params.channelId;
    }
    // 日期范围-起始时间
    if (params.dateStart) {
      queryParams.begin_pubdate = params.dateStart;
    }
    // 日期范围-截止时间
    if (params.dateEnd) {
      queryParams.end_pubdate = params.dateEnd;
    }
    // 分页
    queryParams.page = params.page;
    queryParams.per_page = params.pageSize;
    // 最终给接口的数据
    console.log('最终给接口的数据', queryParams);

    const res = await http.get('/mp/articles', { params: queryParams });

    console.log('文章列表res', res);

    // 把数据格式做转化，保存到reducer
    dispatch({
      type: 'article/getArticles',
      payload: {
        list: res.data.data.results.map((item) => {
          return {
            ...item,
            cover: item.cover.images[0],
          };
        }),
        total: res.data.data.total_count,
      },
    });
  };
};

// 删除文章
export const deleteArticle = (id) => {
  return async (dispatch) => {
    // 删除文章
    const res = await http.delete(`/mp/articles/${id}`);
    console.log('delete res', res);
  };
};

// 发表文章
export const publishArticle = (data) => {
  return async (dispatch) => {
    // 组装数据
    console.log('发表文章', data);
    const postData = {
      title: data.values.title,
      content: data.values.content,
      channel_id: data.values.channelId,
      cover: {
        type: data.values.type,
        images: data.fileList.map((item) => item.response.data.url),
      },
    };
    // 发表状态
    const isDraft = data.publishType === 'draft' ? true : false;
    console.log('格式化后的数据', postData);
    if (data.articleId) {
      // 编辑
      const res = await http.put(
        `/mp/articles/${data.articleId}?draft=${isDraft}`,
        postData
      );
      console.log('编辑', res);
    } else {
      // 发布
      const res = await http.post(`/mp/articles?draft=${isDraft}`, postData);
      console.log('发布', res);
    }
  };
};
